package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Permission;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl  implements PermissionService{

    @Autowired
    private PermissionDao permissionDao;
    //查询全部
    public List<Permission> findAll() {
        return permissionDao.findAll();
    }

    //分页查询
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();//ThreadLocal
        PageHelper.startPage(currentPage,pageSize);//分页插件，会在执行sql之前将分页关键字追加到SQL后面
        Page<Permission> page = permissionDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void edit(Permission permission) {
        permissionDao.edit(permission);
    }

    @Override
    public void add(Permission permission) throws Exception {
        Date da = new Date();
        DateUtils.parseDate2String(da);
        permission.setCreateDate(da);
        permissionDao.add(permission);

        System.out.println(permission);
    }

    @Override
    public void delete(Integer id) {
        List<Integer> roleIds = new ArrayList<>();
        roleIds= permissionDao.selectCountByPermission(id);
        if (roleIds.size() > 0){
            //已经被关联，不能删除
            throw new RuntimeException(MessageConstant.DELETE_CHECKITEM_FAIL);
        }else{
            //可以删除
            permissionDao.delete(id);
        }

        permissionDao.delete(id);
    }

    @Override
    public Permission findById(Integer id) {
        return permissionDao.findById(id);
    }


}
